import json
from datetime import datetime

from app import db
from app.common.json_encoder import JSONEncoder


class BaseModel(db.Model):
    """基类"""
    __abstract__ = True
    create_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    update_at = db.Column(db.DateTime,
                          default=datetime.now,
                          onupdate=datetime.now,
                          comment='更新时间')

    # 获取类所有属性，下划线开头的不获取
    def keys(self):
        attr = []
        for name, value in vars(self).items():
            if not name.startswith('_'):
                attr.append(name)
        return attr

    # 获取子元素属性
    def __getitem__(self, item):
        return getattr(self, item)

    # 转JSON字符串
    def to_json(self):
        return json.dumps(self, cls=JSONEncoder, ensure_ascii=False)

    # flask-json需要
    def __json__(self):
        return dict(self)
